package com.model;

import com.model.math.Point3D;
import org.lwjgl.PointerBuffer;
import org.lwjgl.assimp.*;
import org.lwjgl.system.MemoryStack;

import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.List;

public class ModelLoader {
    
    public static Point3D[] loadGLTFFile(String filePath) {
        // 初始化Assimp
        AIScene scene = Assimp.aiImportFile(filePath, 
            Assimp.aiProcess_Triangulate | 
            Assimp.aiProcess_GenNormals | 
            Assimp.aiProcess_JoinIdenticalVertices
        );

        if (scene == null) {
            throw new RuntimeException("Error loading model: " + Assimp.aiGetErrorString());
        }

        try {
            List<Point3D> vertices = new ArrayList<>();
            
            // 遍历所有网格
            int meshCount = scene.mNumMeshes();
            PointerBuffer meshes = scene.mMeshes();
            
            for (int i = 0; i < meshCount; i++) {
                AIMesh mesh = AIMesh.create(meshes.get(i));
                
                // 获取顶点数据
                AIVector3D.Buffer verticesBuffer = mesh.mVertices();
                while (verticesBuffer.remaining() > 0) {
                    AIVector3D vertex = verticesBuffer.get();
                    vertices.add(new Point3D(
                        vertex.x(),
                        vertex.y(),
                        vertex.z()
                    ));
                }
            }
            
            return vertices.toArray(new Point3D[0]);
            
        } finally {
            // 释放资源
            Assimp.aiReleaseImport(scene);
        }
    }
}